package org.car.world.common.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;

/**
 * @author Administrator
 * @ClassName: BASE64DecodedMultipartFile
 * @Description: base64解析工具类
 * @date Dec 22, 2018
 */
public class BASE64DecodedMultipartFile {

    /**
     * 标识方法是否执行成功字段
     */
    public static boolean FIlEFLAG;

    /**
     * @param @param  basedata
     * @param @param  request
     * @param @return 参数
     * @return boolean    返回类型
     * @throws
     * @Title: Base64UpdateFile
     * @Description: 解码并并保存为图片
     */

    @SuppressWarnings("restriction")
    public static String Base64UpdateFile(String basedata, String filetype, HttpServletRequest request) {
        String filepath = "";
        String newpath = basedata.split(",")[1];
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(newpath);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 项目在容器中实际发布运行的根路径
            String realPath = request.getSession().getServletContext().getRealPath("/");
            //生成图片
            String path = "templates\\upload\\";
            String suffix = "";
            String type = filetype.split("/")[1];
            if (type.equals("jpeg") || type == "jpeg") {
                suffix = ".jpg";
            } else if (type.equals("png") || type == "png") {
                suffix = ".png";
            } else if (type.equals("gif") || type == "gif") {
                suffix = ".gif";
            } else if (type.equals("webp") || type == "webp") {
                suffix = ".webp";
            }
            filepath = path + UUID.randomUUID() + suffix;
            String newactiv = realPath + filepath;
            OutputStream out = new FileOutputStream(newactiv);
            out.write(bytes);
            out.flush();
            out.close();
            FIlEFLAG = true;
            return filepath;
        } catch (Exception e) {
            FIlEFLAG = true;
        } finally {
            System.err.println("方法执行完毕");
        }
        return filepath;
    }

}
